#!/opt/uss-fe/bin/perl
use 5.008;
use strict;
use warnings;
use Encode;
use MIME::Base64 qw(encode_base64);
use HTML::Template::Pro;
use POSIX qw(strftime);
use USS::CGI::Member;
use USS::Form;
use USS::Japanese;
use Digest::SHA qw(sha256_base64);

my @params = qw(
    action
    uke_datetime
    ec_tran_id
    Result
    Error_Variable
    cardno_err
    card_Result
    card_kaiin_no_Result
    yuko_mmyy_Result
    card_kakunin_no_Result
    masked_card_kaiin_no
    request_kamei_id
    kamei_id
    auth_code
);

my %form   = ();

my $USS = USS::CGI::Member->new();

my $jp = USS::Japanese->new( "HINT" => $USS->param("_code_hint") || "" );

my $log_str = "";
foreach (@params) {
    $form{$_} =
        defined $USS->param($_) ? $jp->code_to_euc( $USS->param($_) ) : "";
	$log_str .= sprintf( "%s=>[%s] ", $_, $form{$_} );
}
if ( !$form{action} ) {
    $USS->logging( sprintf "nicos_card param %s", $log_str );
    print "Content-type: text/plain; charset=euc-jp\n\n success";
}elsif ( $form{action} eq "get_conf" ) {
    my %conf = ();
    if ( !read_conf( \%conf, "/opt/uss-fe/etc/nicos_card.conf" ) ) {
        $USS->error_page( "システムエラー", "can't read conf" );
    }
    my $nicos_info = $conf{nicos_info};

    my $current_date = strftime( "%Y%m%d%H%M", localtime );

    my $contents = $nicos_info->{kamei_id}.$nicos_info->{auth_code}.$current_date;

#    my $contents = '7700000126000006201710181339';
    my $ascii = "";
		use MLog;
#		wlog($contents,"li0209c.log");
    for(my $i = 0; $i < length($contents); $i++){ 
        my $num = substr($contents,$i,1);
        my $content = sprintf("%1x",unpack("U*", $num));
        $ascii .= $content;
    }
    my $authcode = sha256_base64($contents);
    while (length ($authcode)%4 ) {
        $authcode.= '=' ;
    }

    my $str = hash2Json( $nicos_info );
    print "Content-type: text/plain; charset=euc-jp\n\n", $str;
}

exit(0);

#*****************************************************************************

=head1 METHODS

=head2 hash2Json(HASH hash)

JSON格式文字列を返す

=cut

#*****************************************************************************
sub hash2Json {
    my($hash) = @_;

    my @array = ();
    foreach ( keys %$hash ) {
        if ( $hash->{$_} ) {
            push @array, '"' . $_ . '":"' . $hash->{$_} . '"';
        }
    }

    my $str = sprintf( "{%s}", join( ",", @array ) );

    return $str;
}


